package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/14 9:49
 */
public class Flink09_Window_Aggregate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        env.setParallelism(2);
        // 每隔5s计算这5s内的wordCount
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            //            .keyBy(ws -> ws.getId())
            .keyBy(WaterSensor::getId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .aggregate(
                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
    
                    // 初始化一个累加器
                    @Override
                    public Tuple2<Integer, Long> createAccumulator() {
                        System.out.println("Flink09_Window_Aggregate.createAccumulator");
                        return Tuple2.of(0, 0L);
                    }
    
                    // 累加
                    @Override
                    public Tuple2<Integer, Long> add(WaterSensor value, Tuple2<Integer, Long> acc) {
                        System.out.println("Flink09_Window_Aggregate.add");
                        return Tuple2.of(acc.f0 + value.getVc(), acc.f1 + 1L);
                    }
    
                    // 返回结果
                    @Override
                    public Double getResult(Tuple2<Integer, Long> acc) {
                        System.out.println("Flink09_Window_Aggregate.getResult");
                        return acc.f0 * 1.0 / acc.f1;
                    }
    
                    // 合并两个累加器, 当窗口是会话窗口才会有效
                    @Override
                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> a, Tuple2<Integer, Long> b) {
                        System.out.println("Flink09_Window_Aggregate.merge");
                        return Tuple2.of(a.f0 + b.f0, a.f1 + b.f1);
                    }
                },
                new ProcessWindowFunction<Double, String, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<Double> elements,
                                        Collector<String> out) throws Exception {
                        Double avg = elements.iterator().next();
                        out.collect(key + " " + avg);
                        
                    }
                }
            )
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
